package com.example.onlinemarket.activity;

import androidx.annotation.NonNull;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.onlinemarket.Application;
import com.example.onlinemarket.R;
import com.example.onlinemarket.model.User;
import com.example.onlinemarket.util.JSONUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import static com.example.onlinemarket.Application.dismissProgressDialog;
import static com.example.onlinemarket.Application.isLogout;
import static com.example.onlinemarket.Application.loginUser;
import static com.example.onlinemarket.Application.showProgressDialog;
import static com.example.onlinemarket.util.ActivityUtil.jumpToActivity;
import static com.example.onlinemarket.util.ActivityUtil.jumpToActivityForResult;
import static com.example.onlinemarket.util.FileUtil.externalFilesDir;
import static com.example.onlinemarket.util.FileUtil.makeDir;
import static com.example.onlinemarket.util.HttpUtil.sendHttpRequest;

public class LoginActivity extends BaseActivity {

    //获取权限请求码
    private final int WRITE_EXTERNAL_PERMISSION_REQUEST = 0;

    //Intent请求码
    public static final int REGISTER_REQUEST_CODE = 0;

    private TextView loginMsg;
    private EditText userNameEt;
    private EditText passwordEt;
    private CheckBox keepPwdCb;
    private CheckBox autoLoginCb;
    private Button loginBtn;
    private Button registerBtn;
    private boolean isInfoLegal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //读写权限检查，若没有权限则尝试获取
        if(!Application.checkPermission(LoginActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE))
            Application.requestPermissions(LoginActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_PERMISSION_REQUEST);
        //加载资源
        loadResources();
    }

    //初始化组件
    private void initWidgets() {
        userNameEt = findViewById(R.id.et_login_username);
        passwordEt = findViewById(R.id.et_login_password);
        loginMsg = findViewById(R.id.tv_login_msg);
        keepPwdCb = findViewById(R.id.cb_login_keep_password);
        autoLoginCb = findViewById(R.id.cb_login_auto_login);
        loginBtn = findViewById(R.id.btn_login_login);
        registerBtn = findViewById(R.id.btn_login_register);
    }

    //加载资源
    private void loadResources() {
        //打开加载提示
        showProgressDialog(this);
        //设置布局
        setContentView(R.layout.activity_login);
        //初始化组件
        initWidgets();
        //为组件设置监听器
        setWidgetsListener();
        //初始化环境
        initEnvironment();
        //关闭加载提示
        dismissProgressDialog();
    }

    //加载本地存储信息
    private void loadLocalInfo() {
        SharedPreferences pref = getSharedPreferences("login", MODE_PRIVATE);
        keepPwdCb.setChecked(pref.getBoolean("isPwdKept", false));
        autoLoginCb.setChecked(pref.getBoolean("isAutoLogin", false));
        String userName = pref.getString("userName", "");
        String password = pref.getString("password", "");
        userNameEt.setText(userName);
        passwordEt.setText(password);
        //若勾选了自动登录，则直接登录
        if(!userName.isEmpty()&&!password.isEmpty()&&!isLogout){
            loginBtn.setEnabled(true);
            if(autoLoginCb.isChecked())
                login(userName, password);
        }
    }

    //初始化环境
    private void initEnvironment() {
        new Thread(() -> {
            File file = getExternalFilesDir(null);
            externalFilesDir = file.getPath();
            File userDir = getExternalFilesDir("user");
            File goodDir = getExternalFilesDir("good");
            makeDir(userDir);
            makeDir(goodDir);
        }).start();
    }


    @Override
    protected void onStart() {
        super.onStart();
        //加载本地存储信息
        loadLocalInfo();
        loginMsg.setText("");
    }

    //为组件设置监听器
    private void setWidgetsListener() {
        loginBtn.setOnClickListener(v -> new Thread(() -> {
            String userName = userNameEt.getText().toString();
            String password = passwordEt.getText().toString();
            login(userName, password);
        }).start());
        //点击注册按钮，获取当前输入的用户名和密码，传递到RegisterActivity
        registerBtn.setOnClickListener(v -> new Thread(() -> {
            //显示加载提示框
            runOnUiThread(() -> showProgressDialog(LoginActivity.this));
            Map<String, String> map = new HashMap<>();
            map.put("userName", userNameEt.getText().toString());
            map.put("password", passwordEt.getText().toString());
            jumpToActivityForResult(RegisterActivity.class, map, REGISTER_REQUEST_CODE);
        }).start());
        keepPwdCb.setOnClickListener(v -> {
            //若取消勾选记住密码则同时取消勾选自动登录
            if(!keepPwdCb.isChecked())
                autoLoginCb.setChecked(false);
        });
        autoLoginCb.setOnClickListener(v -> {
            if(autoLoginCb.isChecked())
                keepPwdCb.setChecked(true);
        });
        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override
            public void afterTextChanged(Editable s) {
                String userName = userNameEt.getText().toString().trim();
                if(userName.isEmpty()) {
                    loginMsg.setText("请输入用户名");
                    loginBtn.setEnabled(false);
                    isInfoLegal = false;
                }
                else {
                    String password = passwordEt.getText().toString().trim();
                    if(password.isEmpty()) {
                        loginMsg.setText("请输入密码");
                        loginBtn.setEnabled(false);
                        isInfoLegal = false;
                    }else {
                        loginMsg.setText("");
                        loginBtn.setEnabled(true);
                        isInfoLegal = true;
                    }
                }
            }
        };
        passwordEt.addTextChangedListener(watcher);
        userNameEt.addTextChangedListener(watcher);
        passwordEt.setOnEditorActionListener((v, actionId, event) -> {
            if(isInfoLegal
                    &&((actionId == EditorInfo.IME_ACTION_DONE)||(event.getKeyCode() == KeyEvent.KEYCODE_ENTER))){
                hideKeyboard();//隐藏软键盘
                loginBtn.callOnClick();
            }
            return true;
        });
    }

    //隐藏软键盘
    private void hideKeyboard() {
        passwordEt.clearFocus();
        View decorView = getWindow().peekDecorView();
        if (decorView != null) {
            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(decorView.getWindowToken(), 0);
        }
    }

    //判断用户输入的用户名与密码是否能够登录
    private void login(String userName, String password) {
        runOnUiThread(() -> showProgressDialog(LoginActivity.this, "登录中，请稍后..."));
        new Thread(() -> {
            Map<String,String> map = new HashMap<>();
            map.put("userName", userName);
            map.put("password", password);
            String responseData = sendHttpRequest("/login", "POST", map);
            Log.e("登录返回",responseData);
            //若responseData不为空则表示获取到了User对象对应的JSON字符串，即登录成功
            if(responseData!=null&&!responseData.isEmpty()) {
                if(responseData.equals("Wrong"))
                    runOnUiThread(() -> {
                        loginMsg.setText("用户名或密码错误");
                        loginBtn.setEnabled(false);
                        dismissProgressDialog();
                    });
                else
                    loginInit(responseData);//初始化User和登录环境
            }
            else
                //若responseData为空则表示登录失败，显示错误提示信息
                runOnUiThread(() -> {
                    loginMsg.setText("网络连接异常，请稍后重试");
                    Toast.makeText(this, "网络连接异常，请稍后重试", Toast.LENGTH_SHORT).show();
                    dismissProgressDialog();
                });
        }).start();
    }

    //初始化User和登录环境
    private void loginInit(String userJson) {
        new Thread(() -> {
            runOnUiThread(() -> showProgressDialog(LoginActivity.this, "登录中，请稍候..."));
            //获取登录的User信息
            User user = JSONUtil.fromJson(userJson, User.class);
            if(user.isRole()){
                runOnUiThread(() -> {
                    loginMsg.setText("商家请使用网页端登录");
                    loginBtn.setEnabled(false);
                    dismissProgressDialog();
                });
            }else{
                loginUser = user;
                isLogout = false;
                //获取User头像
                loginUser.getUserImg();
                //保存登录信息 如勾选框和用户名、密码
                saveLoginInfo();
                runOnUiThread(() -> {
                    loginMsg.setText("");
                    Toast.makeText(getApplication(), "登录成功", Toast.LENGTH_SHORT).show();
                });
                //跳转到MainActivity
                jumpToActivity(MainActivity.class);
            }
        }).start();
    }

    //保存登录信息 如勾选框和用户名、密码
    private void saveLoginInfo() {
        new Thread(() -> {
            SharedPreferences.Editor editor = getSharedPreferences("login", MODE_PRIVATE).edit();
            boolean isPwdKept = keepPwdCb.isChecked();
            //根据勾选决定是否保存密码
            String pwd = isPwdKept?loginUser.getPassword():"";
            editor.putBoolean("isPwdKept", isPwdKept);
            editor.putBoolean("isAutoLogin", autoLoginCb.isChecked());
            editor.putString("userName", loginUser.getUserName());
            editor.putString("password", pwd);
            editor.apply();
        }).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            //注册成功则自动登录
            if(requestCode==REGISTER_REQUEST_CODE){
                String userName = data.getStringExtra("userName");
                String password = data.getStringExtra("password");
                userNameEt.setText(userName);
                passwordEt.setText(password);
                login(userName, password);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == WRITE_EXTERNAL_PERMISSION_REQUEST)
            if(!(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED))
                finish();
    }
}